#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import os
import shutil
import subprocess
import sys


def run_command(cmd):
    """
    运行命令并检查结果

    :param cmd: 要运行的命令
    :return: 运行结果
    """
    print(f"运行命令: {cmd}")
    result = subprocess.run(cmd, shell=True, capture_output=True, text=True)
    if result.returncode != 0:
        print(f"命令执行失败: {result.stderr}")
        return False
    return True


def run_tests():
    """
    运行测试，如果测试失败则询问是否继续

    :return:
    """
    print("运行测试...")

    # 检查是否有测试目录和测试文件
    if not os.path.exists("tests"):
        print("未找到 tests 目录，跳过测试")
        return True

    test_files = [f for f in os.listdir("tests") if f.startswith("test_") and f.endswith(".py")]
    if not test_files:
        print("未找到测试文件，跳过测试")
        return True

    # 运行测试
    success = run_command("python -m pytest tests/ -v")

    if not success:
        print("测试失败!")
        response = input("是否继续打包? (y/n): ")
        if response.lower() != 'y':
            print("打包已取消")
            return False

    return True


def main():
    """主打包函数"""
    print("=== DataChunker 打包脚本 ===")

    # 清理旧的构建文件
    print("清理旧的构建文件...")
    for dir_name in ["dist", "build", "data_chunker.egg-info"]:
        if os.path.exists(dir_name):
            shutil.rmtree(dir_name)

    # 运行测试
    if not run_tests():
        return False

    # 构建包
    print("构建包...")
    if not run_command("python setup.py sdist bdist_wheel"):
        print("构建失败")
        return False

    # 检查包
    print("检查包...")
    if os.path.exists("dist"):
        files = os.listdir("dist")
        print(f"构建的文件: {files}")

        # 检查wheel包
        if any(f.endswith('.whl') for f in files):
            print("✓ Wheel包构建成功")

        # 检查源码包
        if any(f.endswith('.tar.gz') for f in files):
            print("✓ 源码包构建成功")

    print("打包完成！")
    return True


if __name__ == "__main__":
    success = main()
    sys.exit(0 if success else 1)
